/**************************************************************************************
 * @file client.js
 * @author TKONIY
 * @description 
 * Client implementation with websocket package[https://www.npmjs.com/package/websocket]
 * who's W3CWebsocket can run on browser, but for simplicity, I use electron as fronthead 
 * instead of browser, with  websocket.client
 * 
 * 其他事件: 
 *         以m:开头的事件为自定义事件, 表示接收到某个特定类型的消息, 如 m:status 表示 status消息。
 *         实现方式是:接收到消息后提取event字段并添加上m:开头, 并将data字段作为参数使用emit()分发。
 * 如何使用: 
 *         若需要在前端项目中引入该模块，删除掉const{app}=require('electron'), 将socket声
 *         明为全局变量并导出, 将UI事件与socket.send()绑定。
 **************************************************************************************/
const { app } = require('electron')
const WebSocket = require('websocket').client

const temperature = 100
const url = 'ws://127.0.0.1:5000'
const wss = new WebSocket()

timerConnectServer = setInterval(() => {
    wss.connect(url)
}, 1000)

wss.on('connect', (socket) => {
    console.log('Server connect.')
    clearInterval(timerConnectServer)

    timerSendStatus = setInterval(() => {
        socket.send(JSON.stringify({
            event: 'status',
            data: {
                temperature: temperature
            }
        }))
    }, 1000)

    socket.on('close', (code, desc) => {
        console.log('Connection closed ' + code + ': ' + desc)
        timerConnectServer = setInterval(() => {
            wss.connect(url)
        }, 1000)
        clearInterval(timerSendStatus)
    })

    socket.on('message', (message) => {
        if (message.type === 'utf8') {
            const ev = JSON.parse(message.utf8Data)
            socket.emit('m:' + ev['event'], ev['data'], socket)
        }
    })

    socket.on('m:status', (data) => {
        console.log('[status]' +
            ' cost:' + data['cost'] +
            ' mode:' + data['mode']
        )
    })

    socket.on('m:interval', (data) => {
        interval = data['interval']
        clearInterval(timerSendStatus)
        timerSendStatus = setInterval(() => {
            socket.send(JSON.stringify({
                event: 'status',
                data: {
                    temperature: temperature
                }
            }))
        }, interval)
        console.log('[interval]' +
            ' interval:', interval)
    })

    socket.on('m:air', (data) => {
        console.log('[air]' +
            ' temperature:' + data['temperature'] +
            ' speed' + data['speed'])
    })

})

wss.on('connectFailed', function (error) {
    console.log('Connect Error: ' + error.toString());
});
